use crate::mapper;
use sea_orm::{ActiveValue, DatabaseConnection};
use sky_common::constant::{message, status};
use sky_pojo::{
    dto::employee::{
        EmployeeDTO, EmployeeLoginDtO, EmployeePageQueryDTO, EmployeePassDTO, EmployeeStatusDTO,
    },
    entities::employee,
    vo::{employee::EmployeeVO, PageResult},
};

pub async fn login(
    db: DatabaseConnection,
    employee_login_dto: EmployeeLoginDtO,
) -> Result<employee::Model, String> {
    let emp = mapper::employee::get_by_username(db, employee_login_dto.username)
        .await
        .unwrap(); // 账号不存在，Internal Server Error

    // 密码错误
    if emp.password != employee_login_dto.password {
        return Err(message::PASSWORD_ERROR.to_string());
    }

    // 用户状态
    if emp.status == status::DISABLE {
        return Err(message::ACCOUNT_LOCKED.to_string());
    }

    return Ok(emp);
}

pub async fn add_employee(
    db: DatabaseConnection,
    employee_dto: EmployeeDTO,
    creator: i64,
) -> Result<employee::Model, String> {
    let _employee = employee::ActiveModel {
        // id: ActiveValue::Set(employee_dto.id),
        id_number: ActiveValue::Set(employee_dto.id_number),
        username: ActiveValue::Set(employee_dto.username),
        name: ActiveValue::Set(employee_dto.name),
        phone: ActiveValue::Set(employee_dto.phone),
        sex: ActiveValue::Set(employee_dto.sex),
        status: ActiveValue::Set(status::ENABLE),
        create_user: ActiveValue::Set(Some(creator)),
        update_user: ActiveValue::Set(Some(creator)),
        password: ActiveValue::Set(employee_dto.password),
        ..Default::default()
    };

    match mapper::employee::insert(db, _employee).await {
        Ok(data) => Ok(data),
        Err(err) => {
            if err.to_string().contains("Duplicate entry") {
                return Err(format!("重复项: 用户名"));
            } else {
                return Err(err.to_string());
            }
        }
    }
}

pub async fn page_query(
    db: DatabaseConnection,
    query: EmployeePageQueryDTO,
) -> Result<PageResult<EmployeeVO>, String> {
    let result = mapper::employee::page_query(db, query)
        .await
        .map_err(|op| op.to_string())?; // 将错误转换为 String 类型并返回

    Ok(result) // 返回结果
}

pub async fn find_by_id(db: DatabaseConnection, id: i64) -> Result<EmployeeVO, String> {
    mapper::employee::find_by_id(db, id).await
}

pub async fn enable_disable(
    db: DatabaseConnection,
    employee_dto: EmployeeStatusDTO,
    modifier: i64,
) -> Result<EmployeeVO, String> {
    let update_model = employee::ActiveModel {
        id: ActiveValue::set(employee_dto.id),
        update_user: ActiveValue::Set(Some(modifier)),
        status: ActiveValue::Set(employee_dto.status),

        ..Default::default()
    };

    // 调用 mapper 层
    mapper::employee::update_employee(db, update_model, employee_dto.id).await
}

pub async fn update_employee(
    db: DatabaseConnection,
    employee_dto: EmployeeDTO,
    modifier: i64,
) -> Result<EmployeeVO, String> {
    let update_model = employee::ActiveModel {
        update_user: ActiveValue::Set(Some(modifier)),
        username: ActiveValue::Set(employee_dto.username),
        name: ActiveValue::Set(employee_dto.name),
        phone: ActiveValue::Set(employee_dto.phone),
        sex: ActiveValue::Set(employee_dto.sex),
        ..Default::default()
    };
    // 调用 mapper 层
    mapper::employee::update_employee(db, update_model, employee_dto.id.unwrap()).await
}

pub async fn modify_password(
    db: DatabaseConnection,
    _emp_pass_dto: EmployeePassDTO,
    modifier: i64,
) -> Result<EmployeeVO, String> {
    let update_model = employee::ActiveModel {
        password: ActiveValue::Set(_emp_pass_dto.new_password),
        update_user: ActiveValue::Set(Some(modifier)),
        ..Default::default()
    };

    mapper::employee::modify_password(
        db,
        update_model,
        _emp_pass_dto.emp_id,
        _emp_pass_dto.old_password,
    )
    .await
}
